package org.yinxue.example.netty.core.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.yinxue.example.netty.core.model.HeartBeatRequest;

import java.util.List;

/**
 * HeartBeatDecoder {@link org.yinxue.example.netty.core.codec}
 *
 * @author zengjian
 * @date 2019/1/1
 * @since 1.0.0
 */
public class HeartBeatDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int readSize = in.readableBytes();
        if (readSize <= 0) {
            return;
        }
        if (readSize >= 20) {
            int optType = in.getInt(0);
            long clientId = in.getLong(4);
            long contentLength = in.getLong(12);
            // TODO 优化为int
            byte[] dst = new byte[(int) contentLength];
            if (readSize >= 20 + contentLength) {
                // 以上不能进行读取，否则第二次调用信息错误
                in.readInt();
                in.readLong();
                in.readLong();
                in.readBytes(dst);
                String content = new String(dst, "utf-8");
                HeartBeatRequest req = new HeartBeatRequest();
                req.setOptType(optType);
                req.setClientId(clientId);
                req.setContentLength(contentLength);
                req.setContent(content);
                out.add(req);
            } else {
                return;
            }
        } else {
            return;
        }
    }
}